import { Tree } from '@angular-devkit/schematics';
import * as path from 'path';
import { DEFAULT_PATH_NAME } from '../../lib/defaults';
import { CrudOptions } from '../../lib/_crud/crud.schema';
import * as fs from 'fs';

type NestCliJson = {
  _rootPath: string;
  sourceRoot?: string;
  crudjs?: {
    schematics?: {
      crud?: CrudOptions;
    };
  };
};
type CrudTransOptions = {
  language?: string;
  filesPath?: string;
  [key: string]: any;
};

import { _JSONFile } from './json-file.util';
const NEST_CLI_PATH = '/nest-cli.json';
export function crudTransform(
  tree: Tree,
  schematicName: string,
  options: CrudTransOptions,
): any {
  const config = getNestCliJson(tree);
  const schematicConfig = config.crudjs?.schematics?.[schematicName] || {};
  // console.log('schematicConfig',schematicConfig);
  // console.log('config',config);

  const target: CrudTransOptions = Object.assign({}, options, schematicConfig);

  const overrideDir = path.join(
    config._rootPath,
    target.filesPath
      ? target.filesPath
      : `${config.sourceRoot || DEFAULT_PATH_NAME}/_crud-tpl`,
    schematicName,
    'files',
  );
  const overridePath = path.resolve(
    __dirname,
    overrideDir,
    target.language || 'ts',
  );
  if (fs.existsSync(overridePath) && fs.readdirSync(overridePath).length > 0) {
    target.filesPath = overrideDir;
  } else {
    target.filesPath = './files';
  }

  return target;
}

export function getNestCliJson(tree: Tree): NestCliJson {
  // const rootPath = '../../../../../test/nest-test/';
  const rootPath = '../../../../../../';
  try {
    const json = new _JSONFile(
      tree,
      path.resolve(__dirname, rootPath) + NEST_CLI_PATH,
    );
    const res = (json.get([]) || {}) as NestCliJson;
    res._rootPath = rootPath;
    return res;
  } catch (error) {
    return {
      _rootPath: rootPath,
    };
  }
}
